package com.sdy.hospitalguard.web.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.common.model.BizException;
import com.sdy.common.model.Response;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.IdCardUtil;
import com.sdy.common.utils.StringUtil;
import com.sdy.hospitalguard.biz.dto.TemporaryCardDTO;
import com.sdy.hospitalguard.biz.model.MatchingPeople;
import com.sdy.hospitalguard.biz.model.TemporaryCard;
import com.sdy.hospitalguard.biz.service.ManagerService;
import com.sdy.hospitalguard.biz.service.MatchingPeopleService;
import com.sdy.hospitalguard.biz.service.TemporaryCardService;
import com.sdy.hospitalguard.biz.utils.ParamChecker;
import com.sdy.mvc.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 临时卡表 前端控制器
 * </p>
 *
 * @author zzq
 * @since 2020-06-02
 */
@Slf4j
@RestController
@RequestMapping("/temporaryCard")
@Api(tags = "临时卡管理接口")
public class TemporaryCardController extends BaseController {
    @Autowired
    private TemporaryCardService temporaryCardService;
    @Autowired
    private MatchingPeopleService matchingPeopleService;
    @Autowired
    private ManagerService managerService;

    @PostMapping("/insertCard")
    @ApiOperation(value = "临时卡新增")
    public Response insertCard(@RequestBody TemporaryCard temporaryCard, HttpServletRequest request) throws BizException {
        Integer userId = getUserId(request);
        Integer roleId = managerService.getById(userId).getRoleId();
        if (roleId != 4) {
            return Response.error("当前用户不显示此界面!");
        }
        String areaName = temporaryCard.getAreaName();
        Integer areaId = temporaryCard.getAreaId();
        Date expireTime = temporaryCard.getExpireTime();
        Date createTime = new Date();
        Assert.notTrue(expireTime.getTime() > createTime.getTime(), "请规范选择临时通行证失效时间!");
        String name = temporaryCard.getName();
        String cardId = temporaryCard.getCardId();
        String phone = temporaryCard.getPhone();
        Assert.isBlank(areaName, "病区名称不能为空!");
        Assert.isNull(areaId, "病区id不能为空!");
        Assert.isNull(expireTime, "失效时间不能为空!");
        Assert.isTrue(!ParamChecker.checkParamRequired(name), "参数<姓名>不能为空!");
        Assert.isTrue(!ParamChecker.checkParamRequired(cardId), "参数<身份证号>不能为空!");
        Assert.isTrue(!IdCardUtil.IDCardValidate(cardId).equals("true"), "身份证号格式错误!");
        if (StringUtil.isNotBlank(phone)) {
            Assert.isTrue(!phone.matches(com.sdy.common.constant.Constants.REGEX_PHONE), "手机号格式错误!");
        }
        LambdaQueryWrapper<MatchingPeople> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MatchingPeople::getCardId, cardId);
        List<MatchingPeople> list = matchingPeopleService.list(queryWrapper);
        Assert.isTrue(list.size() > 0, "该用户身份已注册，无法注册临时通行证!");
        LambdaQueryWrapper<TemporaryCard> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TemporaryCard::getCardId, cardId);
/*        wrapper.eq(TemporaryCard::getName, name);
        if (StringUtil.isNotBlank(phone)) {
            wrapper.eq(TemporaryCard::getPhone, phone);
        } else {
            wrapper.isNull(TemporaryCard::getPhone);
        }*/
        wrapper.ne(TemporaryCard::getStatus, 2);
        TemporaryCard t = temporaryCardService.getOne(wrapper);
        Assert.notNull(t, "此人身份证存在有效的临时通行证，请勿重复添加!");
        temporaryCardService.insertCard(temporaryCard);
        return Response.success("添加成功");
    }

    @GetMapping("/pageData")
    @ResponseBody
    @ApiOperation(value = "临时通行证管理分页数据", response = TemporaryCardDTO.class)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "nameAndPhone", value = "姓名或手机号"),
            @ApiImplicitParam(dataType = "Integer", name = "status", value = "状态，0:有效，1:禁用，2:失效")
    })
    public Response pageManager(Page page, String nameAndPhone, Integer status) throws UnsupportedEncodingException {
        if (null != nameAndPhone) {
            nameAndPhone = URLDecoder.decode(nameAndPhone, StandardCharsets.UTF_8.name());
        }
        Page result = temporaryCardService.pageData(page, nameAndPhone, status);
        List<TemporaryCardDTO> list = result.getRecords();
        SimpleDateFormat sdfStart = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        if (list.size() > 0) {
            for (TemporaryCardDTO l : list) {
                if (l.getExpireTime() != null) {
                    l.setExpireTimeStr(sdfStart.format(l.getExpireTime()));
                }
                if (StringUtils.isNotBlank(l.getPhone())) {
                    l.setPhone(l.getPhone().substring(0, 3) + "****" + l.getPhone().substring(7));
                }
            }
        }
        return Response.success(result.setRecords(list));
    }

    @GetMapping("/download")
    @ApiOperation(value = "人员管理页面的导出", response = TemporaryCardDTO.class)
    public void download(HttpServletResponse response, String nameAndPhone, Integer status) throws UnsupportedEncodingException {
        if (null != nameAndPhone) {
            nameAndPhone = URLDecoder.decode(nameAndPhone, StandardCharsets.UTF_8.name());
        }
        List<TemporaryCardDTO> list = temporaryCardService.listData(nameAndPhone, status);
        SimpleDateFormat sdfStart = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        if (list.size() > 0) {
            for (TemporaryCardDTO l : list) {
                if (l.getStatus() != null) {
                    if (l.getStatus() == 0) {
                        l.setStatusName("有效");
                    } else if (l.getStatus() == 1) {
                        l.setStatusName("禁用");
                    } else if (l.getStatus() == 2) {
                        l.setStatusName("失效");
                    }
                }
                l.setExpireTimeStr(sdfStart.format(l.getExpireTime()));
            }
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String datetime = sdf.format(new Date());
            String fileName = datetime + "临时通行证数据.xlsx";
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
            EasyExcel.write(response.getOutputStream(), TemporaryCardDTO.class).sheet("临时通行证数据").doWrite(list);
        } catch (Exception e) {
            log.error("临时卡数据导出" + e.getMessage(), e);
        }
    }

    @GetMapping("/changeStatus")
    @ApiOperation(value = "状态变更")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "id", value = "表的id")
    })
    public Response changeStatus(Integer id, HttpServletRequest request) throws BizException {
        Integer userId = getUserId(request);
        Integer roleId = managerService.getById(userId).getRoleId();
        if (roleId != 4) {
            return Response.error("当前用户不显示此界面!");
        }
        TemporaryCard temporaryCard = temporaryCardService.getById(id);
        if (temporaryCard == null) {
            return Response.error("请传入正确的主键id!");
        }
        if (temporaryCard.getStatus() == 2) {
            return Response.error("请不要操作失效的临时通行证!");
        }
        temporaryCardService.changeStatus(temporaryCard);
        return Response.success("成功");
    }

}
